package com.example.hookdemo;

import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private Button opbtn;
    private Button playbtn;
    private Button clobtn;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private MediaRecorder videoRecorder;
    private String myVideofilepath = "sdcard/myvideo.3gp";

    private Socket socket;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        opbtn = this.findViewById(R.id.button1);
        playbtn = this.findViewById(R.id.button2);
        clobtn = this.findViewById(R.id.button3);
        videoRecorder = new MediaRecorder();
        surfaceView = this.findViewById(R.id.surfaceView1);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.i("camera", "surface destroyed.");
                surfaceHolder = null;
                stopRecording();
                releaseCamera();
            }
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.i("camera", "surface destroyed");
                surfaceHolder = holder;
            }
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.i("camera", "surface changed.");
                surfaceHolder = holder;
            }
        });

        opbtn.setOnClickListener(argO -> {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads()
                    .detectDiskWrites().detectNetwork().penaltyLog().build());
            try {
                if (socket == null) {
                    socket = new Socket("::", 8080);
                }

                OutputStream outputStream = socket.getOutputStream();
                String test = "点一下";
                byte buffer[] = test.getBytes();
                outputStream.write(buffer);
                outputStream.flush();

                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String data;
                //读取客户端数据
                while((data = br.readLine()) != null){
                    System.out.println("收到服务端：" + data);
                }
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            openCamera();
        });
        playbtn.setOnClickListener(v -> {
            benginRecording();
        });
        clobtn.setOnClickListener(v -> {
            stopRecording();
        });
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        stopRecording();
        releaseCamera();
    }
    protected void stopRecording() {
        // TODO Auto-generated method stub
        Log.i("videoRecorder", "stopRecording...");
        if (videoRecorder != null) {
            videoRecorder.stop();
            videoRecorder.reset();
            videoRecorder.release();
            videoRecorder = null;
            camera.lock();
        }
    }
    private void releaseCamera() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }
    protected void benginRecording() {
        Log.i("videoRecorder", "beginRecording");
        //给摄像头解锁
        camera.unlock();
        //MediaRecorder获取到摄像头的访问权
        videoRecorder.setCamera(camera);
        //设置视频录制过程中所录制的音频来自手机的麦克风
        videoRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        //设置视频源为摄像头
        videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //设置视频录制的输出文件为3gp文件
        videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //设置音频编码方式为AAC
        videoRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //设置录制的视频编码为H.264
        videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        videoRecorder.setVideoSize(176, 144);
        videoRecorder.setVideoFrameRate(20);
        if (!checkSDCard()) {
            Log.e("videoRecorder", "未找到SD卡!");
            return;
        }
        videoRecorder.setOutputFile(myVideofilepath);
        videoRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        try {
            videoRecorder.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        videoRecorder.start();
    }
    private void openCamera() {
        // TODO Auto-generated method stub
        Log.i("videoRecorder", "openCamera.");
        try {
            camera = Camera.open(); // attempt to get a Camera instance
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e("camera", "open camera error!");
            e.printStackTrace();
            return;
        }
        try {
            camera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("camera", "preview failed.");
            e.printStackTrace();
        }
        camera.startPreview();
    }
    private boolean checkSDCard() {
        // 判断SD存储卡是否存在
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
